package org.itboys.store.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.store.cache.BrandLoader;
import org.itboys.store.constant.ProductConstant;
import org.itboys.store.entity.ProductBrand;
import org.itboys.store.service.StoreProductBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
 * 商品品牌
 * @author weisky
 *
 */
@RestController
@RequestMapping("/store/brand")
public class StoreProductBrandController extends BaseController{

	@Autowired
	private StoreProductBrandService storeProductBrandService;
	@Resource(name = "storeBrandLoader")
	private BrandLoader brandLoader;
	
	@RequestMapping("/listToVM")
	public ModelAndView brandVM(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("ace/store/brand");
	}
	
	@RequestMapping("/list")
	public void list(HttpServletRequest request,HttpServletResponse response){
		Page<ProductBrand> page = storeProductBrandService.pageQuery(request);
		JsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}
	
	/**
	 * 保存或者修改
	 * @param productBrand
	 * @param tlogo
	 * @param request
	 * @param response
	 */
	@RequestMapping("/save")
	public void save(ProductBrand productBrand, @RequestParam(value="tlogo",required=false) MultipartFile tlogo,
			HttpServletRequest request,HttpServletResponse response){
		boolean result = storeProductBrandService.insert(productBrand, tlogo);
		brandLoader.clearCache(ProductConstant.CACHE_BRAND);
		if(result){
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}else{
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	@RequestMapping("/getById")
	public void getById(@RequestParam("id") Long id,
			HttpServletRequest request,HttpServletResponse response){
		AjaxUtils.renderJson(response, storeProductBrandService.getById(id));
	}
	
	@RequestMapping("/delete")
	public void delete(@RequestParam("id") Long id,
			HttpServletRequest request,HttpServletResponse response){
		try {
			storeProductBrandService.dele(id);
			brandLoader.clearCache(ProductConstant.CACHE_BRAND);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("/store/brand/delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
}
